import { getToken } from '@/utils/auth';
import { useIMStore } from '@/store/modules/im';

import { MessageVo } from '@/types/IMMessageDTO';
import { IMMessageType } from '@/enmus/IMMessageEnum';

import { useEventSource } from '@vueuse/core';

// 初始化
export const initSSE = async () => {
  if (!getToken() || import.meta.env.VITE_APP_SSE === 'false') {
    return;
  }
  const url = ` ${import.meta.env.VITE_APP_BASE_API}/resource/sse?Authorization=Bearer ${getToken()}&clientid=${import.meta.env.VITE_APP_CLIENT_ID}`;
  const { data, error } = useEventSource(url, [], {
    autoReconnect: {
      retries: 10,
      delay: 3000,
      onFailed() {
        console.log('Failed to connect after 10 retries');
      }
    }
  });
  watch(error, () => {
    console.log('SSE connection error:', error.value);
    error.value = null;
  });

  watch(data, () => {
    if (!data.value) return;
    const message: MessageVo = JSON.parse(data.value);
    // message.sendTime = timeFormat(message.sendTime, 'yyyy-mm-dd hh:MM:ss');
    uni.$emit(message.messageType, message);
    if (!message.ifRead && message.ifUpCount) {
      useIMStore().add(message.messageType);
    }
    if (message.ifHint && message.messageType !== IMMessageType.LOGIN) {
      // modal.showToast(message.messageInfo);
      modal.showIMMessage(message.messageTitle, message.messageInfo);
    }
  });
};

export const closeSSE = async () => {
  if (!getToken() || import.meta.env.VITE_APP_SSE === 'false') {
    return;
  }
  await uni.$u.http.get('/resource/sse/close');
};
